package net.cellkyborg.server;

import java.net.SocketException;

public class server {
	
	public static LoginServer loginServer = null;
	public static PlayerHandler playerHandler = null;
	public static UpdateHandler updateHandler = null;
	public static SQLHandler sqlHandler = null;
	public static NPCHandler npcHandler = null;
	
	public static boolean shutDownServer = false;
	public static long serverTotalUptime = 0;
	private static int cycleTime = 500;
	
	
	public server() {
		
	}
	
	public static void main(String args[]) {
		sqlHandler = new SQLHandler();
		npcHandler = new NPCHandler();
		playerHandler = new PlayerHandler();
		updateHandler = new UpdateHandler();
		updateHandler.loadData();
		
		loginServer = new LoginServer();
		(new Thread(loginServer)).start();

		while (!shutDownServer) {
			long lastTime = System.currentTimeMillis();
			
			playerHandler.process();
			npcHandler.process();
			
			System.gc();
			
			long spentTime = System.currentTimeMillis() - lastTime;
			serverTotalUptime+=spentTime;
			if (spentTime > cycleTime) {
				misc.println("[SERVER ERROR] Computer is too slow for this server. Shuting Down!");
				shutDownServer = true;
			}
			try {
				Thread.sleep(cycleTime - spentTime);
			}
			catch (Exception e) {
				misc.println("[SERVER ERROR] Server is running too fast!");
			}		
		}
		loginServer.shutdown();
		playerHandler.shutdown();
	}
}